﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

using ProjectBase.Core;

using log4net;
using log4net.Appender;

namespace $safeprojectname$.Infrastructure.Factories
{
    public static class LoggingTargets
    {
        public static EventLog TestEventLog
        {
            get
            {
                return EventLog.GetEventLogs()
                    .FirstOrDefault(el => el.Log.IsEqual("ProjectBaseLog"));
            }
        }
        public static IEnumerable<EventLogEntry> TestEventLogEntries
        {
            get
            {
                return TestEventLog
                    .Entries
                    .Cast<EventLogEntry>()
                    .Where(entry => entry.Source.IsEqual("ProjectBaseApplication"))
                    .Take(1);
                //.OrderByDescending(entry => entry.TimeWritten);
            }
        }

        public static void RestoreLogs()
        {
            //if (EventLog.SourceExists("ProjectBaseApplication"))
            //{
            //    EventLog.DeleteEventSource("ProjectBaseApplication");
            //}
            //if (EventLog.Exists("ProjectBaseLog"))
            //{
            //    EventLog.Delete("ProjectBaseLog");
            //}
        }

        public static MemoryAppender GetCurrentMemoryAppender()
        {
            var repositories = LogManager.GetAllRepositories();
            foreach (var loggerRepository in repositories)
            {
                foreach (var appender in loggerRepository.GetAppenders())
                {
                    var memoryAppender = appender as MemoryAppender;
                    if (memoryAppender.Is())
                    {
                        return memoryAppender;
                    }
                }
            }
            return null;
        }
    }
}
